#include "TextBuilder.h"
#include "HTMLBuilder.h"
#include "Director.h"
#include <string>
#include <cstring>
#include <fstream>
#include <iostream>

void push_back(std::vector<char>& c, std::string& str)
{
    auto iter = str.begin();
    while(iter != str.end())
        c.push_back(*iter);
}

/* TextBuilder implementations */

// finishes documents
void TextBuilder::close()
{
    std::string str = "====================\n"; 
    oss << str;
}

void TextBuilder::makeItems(std::string strArr[], size_t size)
{
    for(int i=0; i < size; i++)
    {
        oss << strArr[i] << "\n";
    }
    oss << "\n";
}

void TextBuilder::makeString(const char* str)
{
    oss << str << "\n";
}

void TextBuilder::makeTitle(const char* str)
{
    std::string s = "====================\n"; 
    oss << s;
    // add [] for title 
    oss << "[ ";
    oss << str;
    oss << " ]\n";
}

std::string TextBuilder::toString()
{
    return oss.str();
}

/* HTMLBuilder implements */

void HTMLBuilder::close()
{
    oss << "</body></html>";
    // save to file 
    std::ofstream file("./" + filename, std::ios::out);
    if(!file.is_open())
    {
        std::cerr << "[error] file openning failure." << std::endl;
        exit(-1);
    }
    file << oss.str();
    file.close();
}

void HTMLBuilder::makeItems(std::string strArr[], size_t len)
{
    oss << "<ul>";
    for(int i = 0; i < len; i++)
        oss << "<li>" << strArr[i] << "</li>";
    oss << "</ul>";
}

void HTMLBuilder::makeString(const char* str)
{
    oss << "<p>" << str << "</p>";
}

void HTMLBuilder::makeTitle(const char* title)
{
    filename.assign(title);
    filename += ".html";
    
    oss << "<html><head><title>" << title << "</title></head><body>";
    oss << "<h1>" << title << "</h1>";
}

std::string HTMLBuilder::getFileName()
{
    return filename;
}

// edit documents
void Director::construct()
{
    builder->makeTitle("Greetings");
    builder->makeString("> 上午到下午 <");
    std::string strArr[2] = {"上午好.", "下午好."};
    builder->makeItems(strArr, 2);
    builder->makeString("> 晚上 <");
    std::string nightStr[3] = {
        "晚上好.",
        "晚安.",
        "再见."
    };
    builder->makeItems(nightStr, 3);
    builder->close(); 
}
